﻿using System;
using System.Collections.Generic;
using System.Data.Entity.Validation;
using System.Linq;
using System.Text;
using INSTA.StockApplication.DAL;

namespace INSTA.StockApplication.BLL
{
    public class Customer
    {
        public bool AddUser(UTILISATEUR user, int type)
        {
            //AJOUT DE L'UTILISATEUR
            var context = new ApplicationStockEntities();
            context.Set<UTILISATEUR>().Add(user);

            //CREATION DE L'EMPLOYEE
            var client = new CLIENT();
            client.ID = user.ID;
            context.Set<CLIENT>().Add(client);
            return save(context);
        }

        private bool save(ApplicationStockEntities context)
        {
            try
            {
                context.SaveChanges();
            }
            catch (DbEntityValidationException e)
            {
                foreach (var s in e.EntityValidationErrors)
                {
                    Console.WriteLine("Entite : {0} etat {1} : ", s.Entry.Entity.GetType().Name, s.Entry.State);
                    foreach (var v in s.ValidationErrors)
                    {
                        Console.WriteLine("Propriete {0}, erreur {1} : ", v.PropertyName, v.ErrorMessage);
                    }
                }
                return false;
            }
            return true;
        }

        public bool DeleteCustomerFromDatabase(int id)
        {
            var context = new ApplicationStockEntities();
            CLIENT c = context.CLIENTs.First(i => i.ID == id);
            context.CLIENTs.Remove(c);
            save(context);
            return true;
        }

        public List<View_Client1> GetListOfUsersFromDatabase()
        {
            var context = new ApplicationStockEntities();
            return context.View_Client1.ToList();
        }
    }
}
